package com.bootdo.IM.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bootdo.IM.domain.EasemobToken;
import com.bootdo.IM.domain.EasemobUser;
import com.bootdo.IM.service.EasemobUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

/**
 * @author Administrator
 *
 */
@Component("easemobUserService")
public class EasemobUserServiceImpl implements EasemobUserService {

	private static Logger logger = LoggerFactory.getLogger(EasemobUserServiceImpl.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.meipinjie.easemob.service.EasemobUserService#queryEasemobToken(java.
	 * lang.String, java.lang.String, java.lang.String, java.lang.String,
	 * java.lang.String)
	 */
	public EasemobToken queryEasemobToken(String easemobUrl, String orgName, String appName, String clientId,
			String clientSecret) {

		String url = easemobUrl + "/" + orgName + "/" + appName + "/token";
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("client_id", clientId);
		paramMap.put("client_secret", clientSecret);
		paramMap.put("grant_type", "client_credentials");

		EasemobToken token = null;
		String result = this.httpClientInvoke(url, orgName, appName, paramMap, null);
		token = JSON.parseObject(result, EasemobToken.class);
		return token;
	}

	/**
	 * @param easemobUrl
	 * @param orgName
	 * @param appName
	 * @param paramMap
	 * @return
	 */
	private String httpClientInvoke(String easemobUrl, String orgName, String appName, Map<String, String> paramMap,
			String token) {
		// 创建默认的httpClient实例.
		CloseableHttpClient httpclient = HttpClients.createDefault();
		String result = null;
		String json = JSON.toJSONString(paramMap);

		HttpPost hPost = new HttpPost(easemobUrl);

		hPost.setHeader("Content-Type", "application/json");

		if (StringUtils.isNotBlank(token)) {
			hPost.setHeader("Authorization", "Bearer " + token);
		}
		CloseableHttpResponse response = null;

		try {

			hPost.setEntity(new StringEntity(json, Charset.forName("UTF-8")));
			response = httpclient.execute(hPost);
			int statusCode = response.getStatusLine().getStatusCode();
			System.out.println("返回参数：" + statusCode);
			if (200 == statusCode) {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					result = EntityUtils.toString(entity, "UTF-8");
				}
			}
		} catch (UnsupportedEncodingException e) {
			logger.error("httpclient 调用出错", e);
		} catch (ClientProtocolException e) {
			logger.error("httpclient 调用出错", e);
		} catch (IOException e) {
			logger.error("httpclient 调用出错", e);
		}
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 注册单个用户
	 * @see
	 * com.meipinjie.easemob.service.EasemobUserService#createEasemobUser(java.
	 * lang.String, java.lang.String, java.lang.String, java.lang.String,
	 * java.lang.String)
	 */
	public EasemobUser createEasemobUser(String easemobUrl, String orgName, String appName, String userId,
			String password) {

		String url = easemobUrl + "/" + orgName + "/" + appName + "/users";
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("username", userId);
		paramMap.put("password", password);
		String result = this.httpClientInvoke(url, orgName, appName, paramMap, null);
		EasemobUser eu = null;

		eu = StringUtils.isBlank(result) ? null : JSON.parseObject(result, EasemobUser.class);
		return eu;
	}

	/*@Override
	public List<String> queryFriendAndBlacklist(String easemobUrl, String orgName, String appName, String userId,String clientId,String clientSecret,String token) {

	*//*	EasemobToken token = this.queryEasemobToken(easemobUrl, orgName, appName, "YXA6uCXtYN1ZEeau6TnO2lCh6Q",
				"YXA6gNeMpinJ4kF0P-eO3kE6t_tbaAw");
		String tokenStr = token.getAccess_token();*//*
		String url = easemobUrl + "/" + orgName + "/" + appName + "/users/" + userId + "/contacts/users";
		Map<String, String> paramMap = new HashMap<String, String>();
		String result = this.httpClientInvokeGet(url, orgName, appName, paramMap, token);

		List<String> list = new ArrayList<String>();
		if (StringUtils.isNotBlank(result)) {
			EasemobFriend easemobFriend = JSON.parseObject(result, EasemobFriend.class);
			list.addAll(easemobFriend.getData());
		}
		return list;
	}*/

	/**
	 * @param easemobUrl
	 * @param orgName
	 * @param appName
	 * @param paramMap
	 * @return
	 */
	private String httpClientInvokeGet(String easemobUrl, String orgName, String appName, Map<String, String> paramMap,
			String token) {
		// 创建默认的httpClient实例.
		CloseableHttpClient httpclient = HttpClients.createDefault();
		String result = null;
		HttpGet hGet = new HttpGet(easemobUrl);

		hGet.setHeader("Content-Type", "application/json");

		if (StringUtils.isNotBlank(token)) {
			hGet.setHeader("Authorization", "Bearer " + token);
		}
		CloseableHttpResponse response = null;

		try {
			response = httpclient.execute(hGet);
			int statusCode = response.getStatusLine().getStatusCode();
			if (200 == statusCode) {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					result = EntityUtils.toString(entity, "UTF-8");
				}
			}
		} catch (UnsupportedEncodingException e) {
			logger.error("httpclient 调用出错", e);
		} catch (ClientProtocolException e) {
			logger.error("httpclient 调用出错", e);
		} catch (IOException e) {
			logger.error("httpclient 调用出错", e);
		}
		return result;
	}


	/*
	* 查询环信用户是否存在
	* */
	public boolean getEasemobUser(String easemobUrl, String orgName, String appName, String userId) {

		String url = easemobUrl + "/" + orgName + "/" + appName + "/users/"+userId;
		int code = this.httpGetClientInvoke(url, orgName, appName, null);
		if (code == 404) {
			return false;
		} else {
			return true;
		}
	}

	/*
	* get请求
	* */
	private int httpGetClientInvoke(String easemobUrl, String orgName, String appName, String token) {
		// 创建默认的httpClient实例.
		CloseableHttpClient httpclient = HttpClients.createDefault();
		String result = null;
		HttpGet hGet = new HttpGet(easemobUrl);

		CloseableHttpResponse response = null;
		int statusCode = 0;
		try {

			response = httpclient.execute(hGet);
			statusCode = response.getStatusLine().getStatusCode();
			System.out.println("查询环信账户返回参数：" + statusCode);
			return statusCode;
		} catch (UnsupportedEncodingException e) {
			logger.error("httpclient 调用出错", e);
		} catch (ClientProtocolException e) {
			logger.error("httpclient 调用出错", e);
		} catch (IOException e) {
			logger.error("httpclient 调用出错", e);
		}
		return statusCode;
	}

}
